//
//  String+CT.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/18.
//

import UIKit

public extension String {
    ///  去两边的空格
    var trimed: String {
        return self.trimmingCharacters(in: .whitespaces)
    }
    ///  将原始的url编码为合法的url
    var urlEncode: String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) ?? self
    }
    
    ///  将编码后的url转换回原始的url
    var urlDecode: String {
        return self.removingPercentEncoding ?? self
    }
    
    /// to URL?
    var asUrl: URL? { return URL(string: self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? self) }
}

public extension String {
    
    /// string的size
    func strSize(font: UIFont, constraints size: CGSize, options: NSStringDrawingOptions = .usesLineFragmentOrigin, context: NSStringDrawingContext? = nil) -> CGSize {
        let cSize = attributedStr(font: font).boundingRect(with: size, options: options, context: context).size
        return CGSize(width: cSize.width.ceil, height: cSize.height.ceil)
    }
    
    private func attributedStr(font: UIFont) -> NSMutableAttributedString {
        
        let attrStr = NSMutableAttributedString.init(string: self)
        guard count > 0 else {
            return attrStr
        }
        let range = NSMakeRange(0, attrStr.length)
        attrStr.addAttributes([.font: font], range: range)
        return attrStr
    }
   
    var attr: NSAttributedString {
        return NSAttributedString.init(string: self)
    }
    
    // MARK: === 字符串添加字间距,行间距
    ///  字符串添加字间距,行间距（通过转化成AttributedString的方式）
    ///
    /// - Parameter font: 文字字体
    /// - Parameter color: 文字颜色
    /// - Parameter wordSpacing: 文字间距
    /// - Parameter lineSpacing: 行间距
    /// - Parameter lineAlignment: 文字对齐方式
    ///
    /// - Returns: 带有字体,颜色,间距的AttributedString
    func attributedStr(font: UIFont, color: UIColor,
                       wordSpacing: Float = 0,
                       lineSpacing: CGFloat = 0,
                       lineAlignment: NSTextAlignment = .left,
                       lineBreakMode: NSLineBreakMode? = .byTruncatingTail) -> NSMutableAttributedString {
        
        let attr = self.attributedStr(font: font, color: color, wordSpacing: wordSpacing)
        let paragrapnStyle = NSMutableParagraphStyle()
        paragrapnStyle.alignment = lineAlignment
        if let lineBreakMode = lineBreakMode {
            paragrapnStyle.lineBreakMode = lineBreakMode
        }
        let range = NSMakeRange(0, attr.length)
        if lineAlignment == .justified {
            attr.addAttributes([.baselineOffset : NSNumber.init(value: 0.0),
                                .paragraphStyle: paragrapnStyle], range: range)
        } else {
            paragrapnStyle.lineSpacing = CGFloat(lineSpacing)
            attr.addAttribute(.paragraphStyle, value: paragrapnStyle, range: NSMakeRange(0, attr.length))
        }
        return attr
    }
    
    private func attributedStr(font: UIFont, color: UIColor, wordSpacing: Float) -> NSMutableAttributedString {
        
        let attrStr = NSMutableAttributedString.init(string: self)
        guard count > 0 else {
            return attrStr
        }
        let range = NSMakeRange(0, attrStr.length)
        attrStr.addAttributes([.font: font,
                               .foregroundColor: color], range: range)
        guard wordSpacing != 0 else {
            return attrStr
        }
        attrStr.addAttribute(.kern, value: wordSpacing, range: NSMakeRange(0, attrStr.length - 1))
        return attrStr
    }
}

// MARK:- String+Attribute
public extension NSAttributedString {
    
    func size(withConstraints size: CGSize,
              options: NSStringDrawingOptions = .usesLineFragmentOrigin,
              context: NSStringDrawingContext? = nil) -> CGSize {
        let cSize = boundingRect(with: size, options: options, context: context).size
        return CGSize(width: cSize.width.ceil, height: cSize.height.ceil)
    }
}

public extension NSMutableAttributedString {

    // MARK: === 给指定文字添加颜色
    func addAttr(ToStr str: String,
                 font: UIFont,
                 color: UIColor) {
        let nsStr = NSString(string: string)
        let range = nsStr.range(of: str)
        addAttributes([.font: font,
                            .foregroundColor: color], range: range)
    }
    // MARK: === 给文字添加下划线
    func addUnderLine() {
        addAttributes([.underlineStyle: NSUnderlineStyle.single.rawValue], range: NSMakeRange(0, length))
    }
    
    func update(lineAlignment: NSTextAlignment) {
        
        let paragrapnStyle = NSMutableParagraphStyle()
        paragrapnStyle.alignment = lineAlignment
        addAttribute(.paragraphStyle, value: paragrapnStyle, range: NSMakeRange(0, length))
    }
}
